package com.sy.rabbitmq.confirm_listener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.sy.rabbitmq.TestProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息确认模式 -confirm  生产端
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建ConnectionFactory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(TestProperties.getIp());
        factory.setPort(TestProperties.getPort());
        factory.setVirtualHost("/");

        //2.获取Connection
        Connection connection = factory.newConnection();

        //3.获取channel
        Channel channel = connection.createChannel();

        //4.指定消息的投递模式: confirmSelect: 消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_confirm_exchange";
        String routeKey = "confirm.save";

        //5.发送一条消息
        String msg = "Hello RabbitMQ send confirm message!";
        channel.basicPublish(exchangeName,routeKey,null,msg.getBytes());

        //todo 6.添加一个确认监听
        channel.addConfirmListener(
                new ConfirmListener() {
                    @Override
                    public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                        System.out.println("----------ack----------");
                    }

                    @Override
                    public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                        System.out.println("----------no-ack----------");
                    }
                }
        );
    }
}
